﻿using Shop.Collect.Helper;
using Shop.Model.DB;
using Shop.Repository;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;

namespace Shop.Collect.lmpl
{
    internal class CouponCodeCollect : ICouponCodeCollect
    {
        private readonly ICouponCodeRepository _Repository;

        public CouponCodeCollect (ICouponCodeRepository repository)
        {
            this._Repository = repository;
        }

        public void Sync (long couponId, int num)
        {
            List<DBShopCouponCode> codes = new List<DBShopCouponCode>(num);
            num.For(c =>
            {
                long id = IdentityHelper.CreateId();
                codes.Add(new DBShopCouponCode
                {
                    Id = id,
                    CouponCode = CouponCodeHelper.CreateCode(id),
                    CouponId = couponId,
                    IsReceive = false
                });
            });
            if (this._Repository.IsExist(c => c.CouponId == couponId))
            {
                this._Repository.Sync(couponId, codes);
                return;
            }
            this._Repository.Adds(codes);
        }
    }
}
